/*
 * Copyright (c) 2020-2021, SERI Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-29     Lyons        first version
 */

#include "__def.h"

#include "rtthread.h"
#include "timer.h"
#include "xprintf.h"

#define THREAD_PRIORITY     (RT_THREAD_PRIORITY_MAX / 3)
#define THREAD_STACK_SIZE   (1024)
#define THREAD_TICK         (2)

static struct rt_thread t1;
static rt_uint8_t t1_stack[THREAD_STACK_SIZE];

static struct rt_thread t2;
static rt_uint8_t t2_stack[THREAD_STACK_SIZE];

static void t1_entry(void *parameter)
{
    xprintf("t1:loop\n");

    while (1)
    {
        xprintf("t1\n");
    }
}

static void t2_entry(void *parameter)
{
    xprintf("t2:loop\n");

    while (1)
    {
        xprintf("t2\n");
    }
}

int main()
{
    xprintf("hello, yu-heng.\n");

    rt_thread_init(&t1, "t1",
                   t1_entry, RT_NULL,
                   &t1_stack[0], sizeof(t1_stack),
                   THREAD_PRIORITY,
                   THREAD_TICK);

    rt_thread_init(&t2, "t2",
                   t2_entry, RT_NULL,
                   &t2_stack[0], sizeof(t2_stack),
                   THREAD_PRIORITY,
                   THREAD_TICK);

    rt_thread_startup(&t1);
    rt_thread_startup(&t2);

    timer_init(TIM1, CPU_FREQ_MHZ-1, (1000/RT_TICK_PER_SECOND)*1000);
    timer_control(TIM1, TIM_EN);

    while (1) {
        xprintf("loop\n");
    }

    return 0;
}

void timer1_handler(void)
{
#ifdef SIMULATION
    static uint32_t simulation_count = 0;

    simulation_count ++;
    write_csr(mtval, simulation_count);

    if (simulation_count >= SIMULATION_COUNT) {
        simulation(0x4);
    }
#endif

    extern void rt_os_tick_callback(void);
    rt_os_tick_callback();
}